package com.wing.cabinet.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.cabinet.dao.AboveTheQuotaApplyDao;
import com.wing.cabinet.dao.AboveTheQuotaApplyProductDao;
import com.wing.cabinet.dao.AuthorityManageDao;
import com.wing.cabinet.model.entity.*;
import com.wing.cabinet.model.request.AuthorityManageForm;
import com.wing.cabinet.model.response.AuthorityManageVO;
import com.wing.cabinet.model.response.AuthorityMaterielVO;
import com.wing.cabinet.model.response.CabinetVO;
import com.wing.cabinet.model.response.CellInventoryInoutVO;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.PageResult;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.model.response.ProductDetailVO;
import com.wing.product.service.ProductDetailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 权限管理表-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class AuthorityManageServiceImpl extends ServiceImpl<AuthorityManageDao, AuthorityManage> implements AuthorityManageService {

    @Autowired
    private CabinetService cabinetService;

    @Autowired
    private ReceiveRecordService receiveRecordService;

    @Autowired
    private AuthorityMemberService authorityMemberService;

    @Autowired
    private CountQuotaService countQuotaService;

    @Autowired
    private AuthorityMaterielService authorityMaterielService;
    @Autowired
    private ProductDetailService productDetailService;
    @Autowired
    private CellInventoryInoutService cellInventoryInoutService;
    @Autowired
    private AboveTheQuotaApplyProductDao aboveTheQuotaApplyProductDao;
    @Autowired
    private AboveTheQuotaApplyDao aboveTheQuotaApplyDao;

    private ExecutorService executorService= Executors.newFixedThreadPool(10);

    @Override
    public int add(AuthorityManageForm authorityManageForm) {
        //校验
        AuthorityManage authorityManage =new AuthorityManage();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(AuthorityManage.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(authorityManageForm, authorityManage, copyOptions);
        authorityManage.setPracticalLineOfCredit(authorityManageForm.getCreditAmount());
        authorityManage.setPracticalCreditQuantity(authorityManageForm.getCreditQuantity());
        //if(authorityManageForm.getCabinetId() != null){
          //  Cabinet cabinet = cabinetService.getById(authorityManageForm.getCabinetId());
           // authorityManage.setCabinetCode(cabinet.getCode());
        //}
        int a = baseMapper.insert(authorityManage);
        if (authorityManageForm.getAuthorityMaterielList().size()!=0){//权限组限制物料
            for(AuthorityMateriel authorityMateriel:authorityManageForm.getAuthorityMaterielList()){
                authorityMateriel.setManageId(authorityManage.getId());
                authorityMateriel.setRealNumber(authorityMateriel.getNumber());
                authorityMateriel.setRealAmount(authorityMateriel.getAmount());
            }
            if(!authorityMaterielService.saveBatch(authorityManageForm.getAuthorityMaterielList())){
                return  0;
            }
        }else{//权限组不限制物料 即对所有物料进行管控
            List<ProductDetail> list = productDetailService.list();
            for (int i = 0; i < list.size(); i++) {
                if(list.get(i).getSkuCode()!=null){
                    AuthorityMateriel authorityMateriel = new AuthorityMateriel();
                    authorityMateriel.setManageId(authorityManage.getId());
                    authorityMateriel.setSkuCode(list.get(i).getSkuCode());
                    authorityMateriel.setRealNumber(authorityMateriel.getNumber());
                    authorityMateriel.setRealAmount(authorityMateriel.getAmount());
                    if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.money)){
                        //权限组授信类型 金额
                        authorityMateriel.setAmount(authorityManage.getLineOfCredit());
                    }else{
                        //权限组授信类型 数量
                        authorityMateriel.setNumber(authorityManage.getAuthorizedQuantity());
                    }
                    authorityMaterielService.save(authorityMateriel);
                }
            }
        }
        return a;
    }

    @Override
    public List<AuthorityManageVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<AuthorityManageVO> pageList4app(Page page, Map<String, Object> params) {
        List<AuthorityManageVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public AuthorityManageVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public int enable(Long id,String type) {
        AuthorityManageVO manageVO = baseMapper.get4appById(id);
        if(manageVO!=null && StringUtils.isNotBlank(type)){
            AuthorityManage authorityManage = new AuthorityManage();
            authorityManage.setId(manageVO.getId());
            if(type.equals("0")){
                authorityManage.setStatus(0l);
            }else if(type.equals("1")){
                authorityManage.setStatus(1l);
            }
            return baseMapper.updateById(authorityManage);
        }
        return 0;
    }

    @Transactional
    @Override
    public int updateAuthorityManage(AuthorityManageForm authorityManageForm) {
        AuthorityManage authorityManage = baseMapper.selectById(authorityManageForm.getId());
        if(authorityManage == null){
            throw new BusinessException("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(AuthorityManage.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(authorityManageForm, authorityManage, copyOptions);
        if(authorityManage.getCreditWay().name().equals("unlimited")||authorityManage.getCreditWay().name().equals("unlimitedQuantity")){
            authorityManage.setAuthorizedQuantity(0);
            authorityManage.setLineOfCredit(new BigDecimal("0"));
        }
        if(authorityManageForm.getCreditType().getValue()==0){
            authorityManage.setAuthorizedQuantity(0);
        }else if(authorityManageForm.getCreditType().getValue()==1){
            authorityManage.setLineOfCredit(new BigDecimal("0"));
        }
        //Map<String, Object> parmas = new HashMap<String, Object>();
        //计算总的实际授信金额和数量
        //实际授信 = 总额度 + 超额审核后的
        //LocalDate nowDate = LocalDate.now();
        //DateTimeFormatter format = DateTimeFormatter .ofPattern("yyyy-MM-dd HH:mm:ss");
        //LocalDate firstDayofMonth = nowDate.with(TemporalAdjusters.firstDayOfMonth());
        //LocalDate lastDayofMonth = nowDate.with(TemporalAdjusters.lastDayOfMonth());
        //LocalDateTime firstDate0fMonth = LocalDateTime.of(firstDayofMonth, LocalTime.MIN);
        //LocalDateTime lastDate0fMonth = LocalDateTime.of(lastDayofMonth, LocalTime.MAX);
        //parmas.put("startCreateTime", format.format(firstDate0fMonth));
        //parmas.put("endCreateTime", format.format(lastDate0fMonth));
        //if(authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
        //    parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
        //}else if(authorityManage.getLineEvaluatePeriod().name().equals("week")){//每周
        //    parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.MONDAY)), LocalTime.MIN));
        //}else if(authorityManage.getLineEvaluatePeriod().name().equals("month")){//每月
        //    parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN));
        //}else if(authorityManage.getLineEvaluatePeriod().name().equals("quarter")){//每季度
        //    parmas.put("startCreateTime",LocalDateTime.of(LocalDate.of(LocalDate.now().getYear(),LocalDate.now().getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
        //}else if(authorityManage.getLineEvaluatePeriod().name().equals("year")){//每年
        //    parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN));
        //}
        //parmas.put("endCreateTime",LocalDateTime.now());
        //parmas.put("authorityManageId", authorityManage.getId());
        //BigDecimal applyPrice = aboveTheQuotaApplyDao.getSumApplyPrice(parmas);
        //BigDecimal applyQuantity = aboveTheQuotaApplyDao.getSumApplyQuantity(parmas);
        if(null == authorityManage.getCreditAmount()){
            authorityManage.setCreditAmount(new BigDecimal(0));
        }
        if(null == authorityManage.getCreditQuantity()){
            authorityManage.setCreditQuantity(0);
        }
        //
        //authorityManage.setPracticalLineOfCredit(authorityManage.getCreditAmount());
        //authorityManage.setPracticalCreditQuantity(authorityManage.getCreditQuantity());

        //authorityManage.setPracticalLineOfCredit(authorityManage.getPracticalLineOfCredit().add(null==applyPrice ? new BigDecimal(0) : applyPrice));
        //Integer practicalCreditQuantity = null==applyQuantity ? 0 : applyQuantity.intValue();
        //authorityManage.setPracticalCreditQuantity(authorityManage.getPracticalCreditQuantity() + practicalCreditQuantity);

        int result = baseMapper.updateById(authorityManage);

        //这个权限组已经有了的物料
        List<AuthorityMaterielVO> authorityMaterielVOList=authorityMaterielService.list4app(new HashMap(){{put("manageId",authorityManageForm.getId());}});


        if(authorityManageForm.getAuthorityMaterielList()!=null){
            List<Long> ids = new ArrayList<>();
            for (int i = 0; i < authorityManageForm.getAuthorityMaterielList().size(); i++) {
                if (authorityManageForm.getAuthorityMaterielList().get(i).getId()!=null && authorityManageForm.getAuthorityMaterielList().get(i).getId()!=0){//修改已经有的
                    ids.add(authorityManageForm.getAuthorityMaterielList().get(i).getId());
                    AuthorityMateriel authorityMateriel = new AuthorityMateriel();
                    CopyOptions copyOptions1 = CopyOptions.create()
                            .setEditable(AuthorityMateriel.class)
                            .setIgnoreError(true)
                            .setIgnoreNullValue(true);
                    BeanUtil.copyProperties(authorityManageForm.getAuthorityMaterielList().get(i), authorityMateriel, copyOptions1);

                    //计算物料的实际授信额度
                    Map<String, Object> productParmas = new HashMap<String, Object>();
                    //计算总的实际授信金额和数量
                    //实际授信 = 总额度 + 超额审核后的
                    if(authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                        productParmas.put("startCreateTime",LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("week")){//每周
                        productParmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.MONDAY)), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("month")){//每月
                        productParmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                        productParmas.put("startCreateTime",LocalDateTime.of(LocalDate.of(LocalDate.now().getYear(),LocalDate.now().getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("year")){//每年
                        productParmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN));
                    }
                    productParmas.put("endCreateTime",LocalDateTime.now());
                    productParmas.put("authorityManageId", authorityManage.getId());
                    productParmas.put("skuCode", authorityMateriel.getSkuCode());
                    BigDecimal skuApplyPrice = aboveTheQuotaApplyProductDao.getSumApplyPrice(productParmas);
                    BigDecimal skuApplyQuantity = aboveTheQuotaApplyProductDao.getSumApplyQuantity(productParmas);
                    if(null ==authorityMateriel.getAmount()){
                        authorityMateriel.setAmount(new BigDecimal(0));
                    }
                    if(null == authorityMateriel.getNumber()){
                        authorityMateriel.setNumber(0);
                    }
                    authorityMateriel.setRealAmount(authorityMateriel.getAmount().add(null==skuApplyPrice ? new BigDecimal(0) : skuApplyPrice));
                    Integer skuApplyQuantityTemp = null==skuApplyQuantity ? 0 : skuApplyQuantity.intValue();
                    authorityMateriel.setRealNumber(authorityMateriel.getNumber() + skuApplyQuantityTemp);
                    authorityMaterielService.updateById(authorityMateriel);
                    //修改cab_count_quota统计限额
                }else{//新添加的
                    AuthorityMateriel authorityMateriel = new AuthorityMateriel();
                    CopyOptions copyOptions1 = CopyOptions.create()
                            .setEditable(AuthorityMateriel.class)
                            .setIgnoreError(true)
                            .setIgnoreNullValue(true);
                    BeanUtil.copyProperties(authorityManageForm.getAuthorityMaterielList().get(i), authorityMateriel, copyOptions1);
                    //authorityMateriel.setRealAmount(authorityMateriel.getAmount());
                    //authorityMateriel.setRealNumber(authorityMateriel.getNumber());
                    //计算物料的实际授信额度
                    Map<String, Object> productParmas = new HashMap<String, Object>();
                    //计算总的实际授信金额和数量
                    //实际授信 = 总额度 + 超额审核后的
                    if(authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                        productParmas.put("startCreateTime",LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("week")){//每周
                        productParmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.MONDAY)), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("month")){//每月
                        productParmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                        productParmas.put("startCreateTime",LocalDateTime.of(LocalDate.of(LocalDate.now().getYear(),LocalDate.now().getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("year")){//每年
                        productParmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN));
                    }
                    productParmas.put("endCreateTime",LocalDateTime.now());
                    productParmas.put("authorityManageId", authorityManage.getId());
                    productParmas.put("skuCode", authorityMateriel.getSkuCode());
                    BigDecimal skuApplyPrice = aboveTheQuotaApplyProductDao.getSumApplyPrice(productParmas);
                    BigDecimal skuApplyQuantity = aboveTheQuotaApplyProductDao.getSumApplyQuantity(productParmas);
                    if(null ==authorityMateriel.getAmount()){
                        authorityMateriel.setAmount(new BigDecimal(0));
                    }
                    if(null == authorityMateriel.getNumber()){
                        authorityMateriel.setNumber(0);
                    }
                    authorityMateriel.setRealAmount(authorityMateriel.getAmount().add(null==skuApplyPrice ? new BigDecimal(0) : skuApplyPrice));
                    Integer skuApplyQuantityTemp = null==skuApplyQuantity ? 0 : skuApplyQuantity.intValue();
                    authorityMateriel.setRealNumber(authorityMateriel.getNumber() + skuApplyQuantityTemp);
                    authorityMateriel.setManageId(authorityManage.getId());
                    authorityMaterielService.save(authorityMateriel);
                }
            }
            for (AuthorityMaterielVO authorityMaterielVO:authorityMaterielVOList){
                if (!ids.contains(authorityMaterielVO.getId())){
                    //刪除沒有了的
                    QueryWrapper<CountQuota> queryWrapper = new QueryWrapper<CountQuota>();
                    queryWrapper.eq("authority_manage_id",authorityMaterielVO.getManageId());
                    queryWrapper.eq("sku_code",authorityMaterielVO.getSkuCode());
                    countQuotaService.getBaseMapper().delete(queryWrapper);
                    authorityMaterielService.getBaseMapper().deleteById(authorityMaterielVO.getId());
                }
            }
        }else{
            return 0;
        }
        //单个物料默认限制状态: 0 限制  1不限制
        //if(authorityManage.getAuthotizedStatus() == 0) {
            List<AuthorityMember> authorityMemberList = authorityMemberService.list(new LambdaQueryWrapper<AuthorityMember>().eq(AuthorityMember::getAuthorityManageId, authorityManage.getId()));
            //该权限组是否配置了人员，配置了统计金额
            if (authorityMemberList.size() > 0) {
                for(AuthorityMember authorityMember : authorityMemberList){
                    Map<String, Object> parmas = new HashMap<String, Object>();
                    if(authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                        parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("week")){//每周
                        parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.MONDAY)), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("month")){//每月
                        parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                        parmas.put("startCreateTime",LocalDateTime.of(LocalDate.of(LocalDate.now().getYear(),LocalDate.now().getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("year")){//每年
                        parmas.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN));
                    }
                    parmas.put("endCreateTime",LocalDateTime.now());
                    parmas.put("authorityManageId", authorityManage.getId());

                    if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)) {
                        BigDecimal applyPrice = aboveTheQuotaApplyDao.getSumApplyPrice(parmas);
                        BigDecimal applyQuantity = aboveTheQuotaApplyDao.getSumApplyQuantity(parmas);
                        if(null == authorityManage.getCreditAmount()){
                            authorityManage.setCreditAmount(new BigDecimal(0));
                        }
                        if(null == authorityManage.getCreditQuantity()){
                            authorityManage.setCreditQuantity(0);
                        }
                        authorityManage.setPracticalCreditQuantity(authorityManage.getCreditQuantity() + applyQuantity.intValue());
                        authorityManage.setPracticalLineOfCredit(authorityManage.getCreditAmount().add(applyPrice));
                        baseMapper.updateById(authorityManage);
                    }
                    if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independent) || authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)) {
                        parmas.put("creator", authorityMember.getUserId());
                        BigDecimal applyPrice = aboveTheQuotaApplyDao.getSumApplyPrice(parmas);
                        BigDecimal applyQuantity = aboveTheQuotaApplyDao.getSumApplyQuantity(parmas);
                        if(null == authorityManage.getCreditAmount()){
                            authorityManage.setCreditAmount(new BigDecimal(0));
                        }
                        if(null == authorityManage.getCreditQuantity()){
                            authorityManage.setCreditQuantity(0);
                        }
                        authorityMember.setPracticalCreditQuantity(authorityManage.getCreditQuantity() + applyQuantity.intValue());
                        authorityMember.setPracticalLineOfCredit(authorityManage.getCreditAmount().add(applyPrice));
                        authorityMemberService.updateById(authorityMember);
                    }

                }
                //asyncStatistical(authorityMemberList,authorityManage);
                asyncCountQuota(authorityMemberList, authorityManage);
            }

       // }
        return result;
    }

    @Override
    public String getCabinetProductAuthority(Long cabinetId) {
        CabinetVO cabinetVO = cabinetService.get4appById(cabinetId);
        //Cabinet cabinet = cabinetService.getCabinetVOByCBelongCabinet(cabinetVO.getBelongCabinet());
        Map paramMap = new HashMap();
        paramMap.put("cabinetId",cabinetVO.getId());
        List<AuthorityManageVO> list = this.list4app(paramMap);
        StringBuffer sb = new StringBuffer();
        for (AuthorityManageVO item : list){
            if(StringUtils.isNotBlank(item.getMaterialId())){
                sb.append(item.getMaterialId()).append(",");
            }
        }
        if(sb != null && sb.length() > 0){
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    void asyncStatistical(List<AuthorityMember> authorityMemberList, AuthorityManage authorityManage){
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
            @Override
            public void afterCommit() {
                executorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            asyncCountQuota(authorityMemberList,authorityManage);
                        }catch (Exception e){
                            log.error("asyncCountQuota fail",e);
                        }

                    }
                });
            }
        });
    }

    void asyncCountQuota(List<AuthorityMember> authorityMemberList, AuthorityManage authorityManage){
        List<AuthorityMateriel> list= authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id",authorityManage.getId()));
        //共享金额或者共享数量
        if (authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.shareQuantity)||authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.share)) {
            Map<String,Object> param = new HashMap();
            param.put("types", Arrays.asList("2,4".split(",")));
            param.put("endCreateTime",LocalDateTime.now());
            if(StringUtils.isNotBlank(authorityManage.getCabinetCode())){
                param.put("mainCabCodes", Arrays.asList(authorityManage.getCabinetCode().split(",")));
            }
            List<CellInventoryInoutVO> cellInventoryInoutVOList = null;

            for (AuthorityMateriel authorityMateriel:list){
                //总数量
                Integer number = 0;
                //总金额
                BigDecimal amount = new BigDecimal(0);

                QueryWrapper<CountQuota> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("authority_manage_id",authorityManage.getId());
                queryWrapper.eq("sku_code",authorityMateriel.getSkuCode());
                //List<CountQuota> listCount = countQuotaService.list(queryWrapper);
                //删除旧的sku 重新生成
                countQuotaService.remove(queryWrapper);

                CountQuota countQuota = new CountQuota();
                countQuota.setAuthorityManageId(authorityManage.getId());
                countQuota.setSkuCode(authorityMateriel.getSkuCode());
                if(authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                    countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.day);
                    countQuota.setResetTime(LocalDateTime.of(LocalDate.now().plusDays(1), LocalTime.MIN));
                }else if(authorityManage.getLineEvaluatePeriod().name().equals("week")){//每周
                    countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.week);
                    countQuota.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.MONDAY)), LocalTime.MIN));
                }else if(authorityManage.getLineEvaluatePeriod().name().equals("month")){//每月
                    countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.month);
                    countQuota.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfNextMonth()), LocalTime.MIN));
                }else if(authorityManage.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                    countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.quarter);
                    countQuota.setResetTime(LocalDateTime.of(LocalDate.of(LocalDate.now().plusMonths(3).getYear(),LocalDate.now().plusMonths(3).getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                }else if(authorityManage.getLineEvaluatePeriod().name().equals("year")){//每年
                    countQuota.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.year);
                    countQuota.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfNextYear()), LocalTime.MIN));
                }
                param.put("skuCode4Detail",authorityMateriel.getSkuCode());

                for(AuthorityMember authorityMember:authorityMemberList){//计算这个组的所有人已经领了的数据
                    param.put("creatorId",authorityMember.getUserId());
                    if(authorityManage.getLineEvaluatePeriod().name().equals("day")) {//每天
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("week")){//每周
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.MONDAY)), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("month")){//每月
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("quarter")){//每季度
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.of(LocalDate.now().getYear(),LocalDate.now().getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                    }else if(authorityManage.getLineEvaluatePeriod().name().equals("year")){//每年
                        param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN));
                    }
                    cellInventoryInoutVOList = cellInventoryInoutService.list4app(param);
                    if (cellInventoryInoutVOList.size()>0){
                        for (CellInventoryInoutVO cellInventoryInoutVO:cellInventoryInoutVOList){
                            amount = amount.add(cellInventoryInoutVO.getTotal());
                            number = number+cellInventoryInoutVO.getQuantityPack();
                        }
                    }
                }

                if(authorityManage.getCreditType().getValue() == 0){
                    countQuota.setCreditType(CountQuota.CreditType.money);
                    //权限组授信额度
                    BigDecimal usableAmount = authorityMateriel.getRealAmount();
                    ////超额申请额度
                    //Map<String, Object> parmas = new HashMap<String, Object>();
                    //parmas.put("authorityManageId", authorityManage.getId());
                    //parmas.put("skuCode", authorityMateriel.getSkuCode());
                    //LocalDate nowDate = LocalDate.now();
                    ////指定日期式
                    //DateTimeFormatter format = DateTimeFormatter .ofPattern("yyyy-MM-dd HH:mm:ss");
                    //LocalDate firstDayofMonth = nowDate.with(TemporalAdjusters.firstDayOfMonth());
                    //LocalDate lastDayofMonth = nowDate.with(TemporalAdjusters.lastDayOfMonth());
                    //LocalDateTime firstDate0fMonth = LocalDateTime.of(firstDayofMonth, LocalTime.MIN);
                    //LocalDateTime lastDate0fMonth = LocalDateTime.of(lastDayofMonth, LocalTime.MAX);
                    //
                    //parmas.put("startCreateTime", format.format(firstDate0fMonth));
                    //parmas.put("endCreateTime", format.format(lastDate0fMonth));
                    //BigDecimal applyPrice = aboveTheQuotaApplyProductDao.getSumApplyPrice(parmas);
                    //
                    //usableAmount.add(null==applyPrice ? new BigDecimal(0) : applyPrice);

                    countQuota.setLineOfCredit(usableAmount);
                    if(authorityManage.getCreditWay().name().equals("share")){//组员共享领用金额
                        countQuota.setCreditWay(CountQuota.CreditWay.share);
                    }
                    if(usableAmount.compareTo(amount)<0){//物料额度小于已经领取的
                        countQuota.setBalance(new BigDecimal(0));//剩余额度就为0
                    }else{//物料额度大于等于已经领取的
                        countQuota.setBalance(usableAmount.subtract(amount));//剩余额度就为物料额度减去已经领取的
                    }
                }

                if(authorityManage.getCreditType().getValue() == 1){
                    countQuota.setCreditType(CountQuota.CreditType.quantity);
                    // 权限组授信数量
                    Integer usableQuantity = authorityMateriel.getRealNumber();
                    ////超额申请额度
                    //Map<String, Object> parmas = new HashMap<String, Object>();
                    //parmas.put("skuCode", authorityMateriel.getSkuCode());
                    //parmas.put("authorityManageId", authorityManage.getId());
                    //LocalDate nowDate = LocalDate.now();
                    //DateTimeFormatter format = DateTimeFormatter .ofPattern("yyyy-MM-dd HH:mm:ss");
                    //LocalDate firstDayofMonth = nowDate.with(TemporalAdjusters.firstDayOfMonth());
                    //LocalDate lastDayofMonth = nowDate.with(TemporalAdjusters.lastDayOfMonth());
                    //LocalDateTime firstDate0fMonth = LocalDateTime.of(firstDayofMonth, LocalTime.MIN);
                    //LocalDateTime lastDate0fMonth = LocalDateTime.of(lastDayofMonth, LocalTime.MAX);
                    //parmas.put("startCreateTime", format.format(firstDate0fMonth));
                    //parmas.put("endCreateTime", format.format(lastDate0fMonth));
                    //BigDecimal applyQuantity = aboveTheQuotaApplyProductDao.getSumApplyQuantity(parmas);
                    //usableQuantity += null==applyQuantity ? 0 : applyQuantity.intValue();

                    //授信数量
                    countQuota.setAuthorizedQuantity(usableQuantity);
                    //授信方式
                    if(authorityManage.getCreditWay().name().equals("shareQuantity")) {//组员共享领用数量
                        countQuota.setCreditWay(CountQuota.CreditWay.shareQuantity);
                    }
                    if(usableQuantity-number<0){//物料数量小于已经领取的
                        countQuota.setResidualQuantity(0);//剩余数量就为0
                    }else{//物料数量大于等于已经领取的
                        countQuota.setResidualQuantity(usableQuantity-number);//剩余数量就为物料数量减去已经领取的
                    }
                }

                countQuotaService.save(countQuota);

            }

        }else{
            //组员独享
            for(AuthorityMember item:authorityMemberList){
                for (AuthorityMateriel authorityMateriel:list){

                    QueryWrapper<CountQuota> quotaQueryWrapper = new QueryWrapper<>();
                    quotaQueryWrapper.eq("receiver_id", item.getUserId());
                    quotaQueryWrapper.eq("sku_code",authorityMateriel.getSkuCode());
                    quotaQueryWrapper.eq("authority_manage_id",authorityManage.getId());
                    //删除旧的sku 重新生成
                    countQuotaService.remove(quotaQueryWrapper);

                    //例如 10月10号创建权限组，周期为每月， 要查询该员工从10月01号到创建权限组时已经领了的金额或者数量，将金额或者数量算入已领取
                    //可领金额或者数量的额度要减去已领取的
                    Map<String,Object> param = new HashMap();
                    param.put("types",Arrays.asList("2,4".split(",")));
                    param.put("creatorId",item.getUserId());
                    param.put("endCreateTime",LocalDateTime.now());
                    param.put("skuCode4Detail",authorityMateriel.getSkuCode());
                    if(StringUtils.isNotBlank(authorityManage.getCabinetCode())){
                        param.put("mainCabCodes", Arrays.asList(authorityManage.getCabinetCode().split(",")));
                    }
                    List<CellInventoryInoutVO> cellInventoryInoutVOList = null;
                    //总数量
                    Integer number = 0;
                    //总金额
                    BigDecimal amount = new BigDecimal(0);

                    CountQuota countQuotaNew = new CountQuota();
                    countQuotaNew.setAuthorityManageId(authorityManage.getId());
                    countQuotaNew.setReceiverId(item.getUserId());
                    countQuotaNew.setReceiverName(item.getUserName());
                    countQuotaNew.setSkuCode(authorityMateriel.getSkuCode());

                    if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.money)){
                        //权限组额度
                        BigDecimal usableAmount = authorityMateriel.getRealAmount();
                        ////超额申请额度
                        //Map<String, Object> parmas = new HashMap<String, Object>();
                        //parmas.put("skuCode", authorityMateriel.getSkuCode());
                        //parmas.put("authorityManageId", authorityManage.getId());
                        //LocalDate nowDate = LocalDate.now();
                        //DateTimeFormatter format = DateTimeFormatter .ofPattern("yyyy-MM-dd HH:mm:ss");
                        //LocalDate firstDayofMonth = nowDate.with(TemporalAdjusters.firstDayOfMonth());
                        //LocalDate lastDayofMonth = nowDate.with(TemporalAdjusters.lastDayOfMonth());
                        //LocalDateTime firstDate0fMonth = LocalDateTime.of(firstDayofMonth, LocalTime.MIN);
                        //LocalDateTime lastDate0fMonth = LocalDateTime.of(lastDayofMonth, LocalTime.MAX);
                        //parmas.put("startCreateTime", format.format(firstDate0fMonth));
                        //parmas.put("endCreateTime", format.format(lastDate0fMonth));
                        //BigDecimal applyPrice = aboveTheQuotaApplyProductDao.getSumApplyPrice(parmas);
                        //
                        //usableAmount.add(null==applyPrice ? new BigDecimal(0) : applyPrice);

                        countQuotaNew.setCreditType(CountQuota.CreditType.money);
                        countQuotaNew.setLineOfCredit(usableAmount);
                        countQuotaNew.setAuthorizedQuantity(0);
                        countQuotaNew.setResidualQuantity(0);
                        //授信类型 金额
                        //独立
                        if(authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independent)){
                            countQuotaNew.setCreditWay(CountQuota.CreditWay.independent);
                            if (authorityManage.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.day)){
                                countQuotaNew.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.day);
                                countQuotaNew.setResetTime(LocalDateTime.of(LocalDate.now().plusDays(1), LocalTime.MIN));
                                param.put("startCreateTime",LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
                            }else if(authorityManage.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.week)){
                                countQuotaNew.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.week);
                                countQuotaNew.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.MONDAY)), LocalTime.MIN));
                                param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.MONDAY)), LocalTime.MIN));
                            }else if(authorityManage.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.month)){
                                countQuotaNew.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.month);
                                countQuotaNew.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfNextMonth()), LocalTime.MIN));
                                param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN));
                            }else if(authorityManage.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.quarter)){
                                countQuotaNew.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.quarter);
                                countQuotaNew.setResetTime(LocalDateTime.of(LocalDate.of(LocalDate.now().plusMonths(3).getYear(),LocalDate.now().plusMonths(3).getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                                param.put("startCreateTime",LocalDateTime.of(LocalDate.of(LocalDate.now().getYear(),LocalDate.now().getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                            }else if(authorityManage.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.year)){
                                countQuotaNew.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.year);
                                countQuotaNew.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfNextYear()), LocalTime.MIN));
                                param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN));
                            }
                            cellInventoryInoutVOList = cellInventoryInoutService.list4app(param);
                            if (cellInventoryInoutVOList.size()>0){
                                for (CellInventoryInoutVO cellInventoryInoutVO:cellInventoryInoutVOList){
                                    amount = amount.add(cellInventoryInoutVO.getTotal());
                                }
                            }
                            if(usableAmount.compareTo(amount)<0){//物料额度小于已经领取的
                                countQuotaNew.setBalance(new BigDecimal(0));//剩余额度就为0
                            }else{//物料额度大于等于已经领取的
                                countQuotaNew.setBalance(usableAmount.subtract(amount));//剩余额度就为物料额度减去已经领取的
                            }
                        }else if(authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.unlimited)){//不限制
                            countQuotaNew.setCreditWay(CountQuota.CreditWay.unlimited);
                        }
                    }

                    if (authorityManage.getCreditType().equals(AuthorityManage.CreditType.quantity)){
                        Integer usableQuantity = authorityMateriel.getRealNumber();

                        countQuotaNew.setCreditType(CountQuota.CreditType.quantity);
                        countQuotaNew.setLineOfCredit(new BigDecimal(0));
                        countQuotaNew.setBalance(new BigDecimal(0));
                        countQuotaNew.setAuthorizedQuantity(usableQuantity);

                        ////超额申请额度
                        //Map<String, Object> parmas = new HashMap<String, Object>();
                        //parmas.put("skuCode", authorityMateriel.getSkuCode());
                        //parmas.put("authorityManageId", authorityManage.getId());
                        //LocalDate nowDate = LocalDate.now();
                        //DateTimeFormatter format = DateTimeFormatter .ofPattern("yyyy-MM-dd HH:mm:ss");
                        //LocalDate firstDayofMonth = nowDate.with(TemporalAdjusters.firstDayOfMonth());
                        //LocalDate lastDayofMonth = nowDate.with(TemporalAdjusters.lastDayOfMonth());
                        //LocalDateTime firstDate0fMonth = LocalDateTime.of(firstDayofMonth, LocalTime.MIN);
                        //LocalDateTime lastDate0fMonth = LocalDateTime.of(lastDayofMonth, LocalTime.MAX);
                        //parmas.put("startCreateTime", format.format(firstDate0fMonth));
                        //parmas.put("endCreateTime", format.format(lastDate0fMonth));
                        //BigDecimal applyQuantity = aboveTheQuotaApplyProductDao.getSumApplyQuantity(parmas);
                        //usableQuantity += null==applyQuantity ? 0 : applyQuantity.intValue();

                        //授信类型 数量
                        if(authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.independentQuantity)){//独立
                            countQuotaNew.setCreditWay(CountQuota.CreditWay.independentQuantity);
                            if (authorityManage.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.day)){
                                countQuotaNew.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.day);
                                countQuotaNew.setResetTime(LocalDateTime.of(LocalDate.now().plusDays(1), LocalTime.MIN));
                                param.put("startCreateTime",LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
                            }else if(authorityManage.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.week)){
                                countQuotaNew.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.week);
                                countQuotaNew.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.MONDAY)), LocalTime.MIN));
                                param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.MONDAY)), LocalTime.MIN));
                            }else if(authorityManage.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.month)){
                                countQuotaNew.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.month);
                                countQuotaNew.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfNextMonth()), LocalTime.MIN));
                                param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN));
                            }else if(authorityManage.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.quarter)){
                                countQuotaNew.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.quarter);
                                countQuotaNew.setResetTime(LocalDateTime.of(LocalDate.of(LocalDate.now().plusMonths(3).getYear(),LocalDate.now().plusMonths(3).getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                                param.put("startCreateTime",LocalDateTime.of(LocalDate.of(LocalDate.now().getYear(),LocalDate.now().getMonth().firstMonthOfQuarter(),1),LocalTime.MIN));
                            }else if(authorityManage.getLineEvaluatePeriod().equals(AuthorityManage.LineEvaluatePeriod.year)){
                                countQuotaNew.setLineEvaluatePeriod(CountQuota.LineEvaluatePeriod.year);
                                countQuotaNew.setResetTime(LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfNextYear()), LocalTime.MIN));
                                param.put("startCreateTime",LocalDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN));
                            }
                            cellInventoryInoutVOList = cellInventoryInoutService.list4app(param);
                            if (cellInventoryInoutVOList.size()>0){
                                for (CellInventoryInoutVO cellInventoryInoutVO:cellInventoryInoutVOList){
                                    number = number+cellInventoryInoutVO.getQuantityPack();
                                }
                            }
                            if(usableQuantity-number<0){//物料数量小于已经领取的
                                countQuotaNew.setResidualQuantity(0);//剩余数量就为0
                            }else{//物料数量大于等于已经领取的
                                countQuotaNew.setResidualQuantity(usableQuantity-number);//剩余数量就为物料数量减去已经领取的
                            }
                        }else if(authorityManage.getCreditWay().equals(AuthorityManage.CreditWay.unlimitedQuantity)){//不限制
                            countQuotaNew.setCreditWay(CountQuota.CreditWay.unlimitedQuantity);
                        }
                    }

                    countQuotaService.save(countQuotaNew);


                }
            }
        }




    }


    @Override
    public PageResult findMateriel(Integer page, Integer limit, String ids, Long authorityManageId, String categoryIds, String skuName, String skuCode, String oldSpecCode, String productBrandName) {
        //限制方式按分类添加
        if (categoryIds!=null&&authorityManageId==null){
            String [] a = categoryIds.split(",");
            List<ProductDetailVO> list = new ArrayList<>();
            for (int i = 0; i <a.length ; i++) {
                HashMap map = new HashMap();
                map.put("productCategoryId",Long.valueOf(a[i]));
                list.addAll(productDetailService.list4app(map));
            }
            if (ids!=null) {//添加时筛选掉已经选择的
                String [] b = ids.split(",");
                List<ProductDetailVO> list1 = new ArrayList<>();
                for (ProductDetailVO productDetailVO:list){
                    for (int i = 0; i <b.length ; i++) {
                        if(b[i]==productDetailVO.getSkuCode()){
                            list1.add(productDetailVO);
                        }
                    }
                }
                list.removeAll(list1);
            }
            /*List<ProductDetailVO> voList = new ArrayList<>();
            if (page==(list.size()/limit)+1){
                for (int i = (page-1)*limit; i < list.size(); i++) {
                    voList.add(list.get(i));
                }
            }else{
                for (int i = (page-1)*limit; i < limit*page; i++) {
                    voList.add(list.get(i));
                }
            }*/
            return new PageResult<>(list, list.size());
        }
        //限制方式按物料 添加
        if (categoryIds==null&&authorityManageId==null){
            HashMap map = new HashMap();
            if(skuName!=null){
                map.put("skuName",skuName);
            }
            if(skuCode!=null){
                map.put("skuCode",skuCode);
            }
            if(oldSpecCode!=null){
                map.put("oldSpecCode",oldSpecCode);
            }
            if(productBrandName!=null){
                map.put("productBrandName",productBrandName);
            }
            Page<ProductDetailVO> pg = new Page<>(page, limit);
            IPage<ProductDetailVO> list = productDetailService.pageList4app(pg,map);
            if (ids!=null) {//添加时筛选掉已经选择的
                List<ProductDetailVO> productDetailVOList = productDetailService.list4app(map);
                String [] b = ids.split(",");
                List<ProductDetailVO> list1 = new ArrayList<>();
                for (ProductDetailVO productDetailVO:productDetailVOList){
                    for (int i = 0; i <b.length ; i++) {
                        if(b[i].equals(productDetailVO.getSkuCode())){
                            list1.add(productDetailVO);
                        }
                    }
                }
                productDetailVOList.removeAll(list1);
                List<ProductDetailVO> voList = new ArrayList<>();
                if (page==(productDetailVOList.size()/limit)+1){
                    for (int i = (page-1)*limit; i < productDetailVOList.size(); i++) {
                        voList.add(productDetailVOList.get(i));
                    }
                }else{
                    for (int i = (page-1)*limit; i < limit*page; i++) {
                        voList.add(productDetailVOList.get(i));
                    }
                }
                return new PageResult<>(voList, productDetailVOList.size());
            }

            return new PageResult<>(list.getRecords(), list.getTotal());
        }


        //查看详情 修改
        if(authorityManageId!=null){
            AuthorityManageVO authorityManageVO = baseMapper.get4appById(authorityManageId);
            if (authorityManageVO.getAstrictMaterial().equals(AuthorityManage.AstrictMaterial.noAstrict)){
                //权限组如果不限制物料 即对所有物料管控
                HashMap map1 = new HashMap();
                map1.put("manageId", authorityManageId);
                List<AuthorityMaterielVO> listAuthorityMateriel = authorityMaterielService.list4app(map1);//该权限组下的物料
                HashMap map = new HashMap();
                List<ProductDetailVO> listProductDetail = productDetailService.list4app(map);//所有的物料
                List<AuthorityMaterielVO> list = new ArrayList<>();
                List<ProductDetailVO> list1 = new ArrayList<>();
                for (int j = 0; j < listProductDetail.size(); j++) {
                    for (int k = 0; k < listAuthorityMateriel.size(); k++) {
                        if (listProductDetail.get(j).getSkuCode()!=null){
                            if (listProductDetail.get(j).getSkuCode().equals(listAuthorityMateriel.get(k).getSkuCode())) {
                                list1.add(listProductDetail.get(j));
                            }
                        }
                    }
                }
                listProductDetail.removeAll(list1);
                for (ProductDetailVO productDetailVO:listProductDetail){
                    AuthorityMaterielVO authorityMaterielVO = new AuthorityMaterielVO();
                    authorityMaterielVO.setProductBrandName(productDetailVO.getBrandName());
                    authorityMaterielVO.setManageId(authorityManageId);
                    if (authorityManageVO.getAuthorizedQuantity()!=null){authorityMaterielVO.setNumber(authorityManageVO.getAuthorizedQuantity());}
                    if (authorityManageVO.getLineOfCredit()!=null){authorityMaterielVO.setAmount(authorityManageVO.getLineOfCredit());}
                    authorityMaterielVO.setPackName(productDetailVO.getPackName());
                    authorityMaterielVO.setProductPic(productDetailVO.getProductPic());
                    authorityMaterielVO.setSkuCode(productDetailVO.getSkuCode());
                    authorityMaterielVO.setSkuName(productDetailVO.getSkuName());
                    authorityMaterielVO.setOldSpecCode(productDetailVO.getOldSpecCode());
                    authorityMaterielVO.setUnitName(productDetailVO.getUnitName());
                    list.add(authorityMaterielVO);
                }
                list.addAll(listAuthorityMateriel);
                return new PageResult<>(list, list.size());
            }else{
                //根据分类 查询出所有物料
                //之前有的 物料限制阈值 为设置好的
                //没有的 为统一设置的值
                //限制方式按分类
                if (authorityManageVO.getRestrictWay().equals(AuthorityManage.RestrictWay.category)) {
                    //根据分类 查询出所有物料
                    //之前有的 物料限制阈值 为设置好的
                    //没有的 为统一设置的值
                    List<AuthorityMaterielVO> list = new ArrayList<>();
                    String authorityManageCategoryIds = authorityManageVO.getMaterialId();
                    String[] a = authorityManageCategoryIds.split(",");
                    for (int i = 0; i < a.length; i++) {
                        HashMap map = new HashMap();
                        map.put("productCategoryId", Long.valueOf(a[i]));
                        List<ProductDetailVO> listProductDetail = productDetailService.list4app(map);//目前该分类下的物料
                        HashMap map1 = new HashMap();
                        map1.put("manageId", authorityManageId);
                        map1.put("categoryId", Long.valueOf(a[i]));
                        List<AuthorityMaterielVO> listAuthorityMateriel = authorityMaterielService.list4app(map1);//之前添加过的该分类的物料
                        List<ProductDetailVO> list1 = new ArrayList<>();
                        for (int j = 0; j < listProductDetail.size(); j++) {
                            for (int k = 0; k < listAuthorityMateriel.size(); k++) {
                                if (listProductDetail.get(j).getSkuCode().equals(listAuthorityMateriel.get(k).getSkuCode())) {
                                    list1.add(listProductDetail.get(j));
                                }
                            }
                        }
                        listProductDetail.removeAll(list1);
                        for (ProductDetailVO productDetailVO:listProductDetail){
                            AuthorityMaterielVO authorityMaterielVO = new AuthorityMaterielVO();
                            authorityMaterielVO.setProductBrandName(productDetailVO.getBrandName());
                            authorityMaterielVO.setCategoryId(Long.valueOf(a[i]));
                            authorityMaterielVO.setManageId(authorityManageId);
                            if (authorityManageVO.getAuthorizedQuantity()!=null){authorityMaterielVO.setNumber(authorityManageVO.getAuthorizedQuantity());}
                            if (authorityManageVO.getLineOfCredit()!=null){authorityMaterielVO.setAmount(authorityManageVO.getLineOfCredit());}
                            authorityMaterielVO.setPackName(productDetailVO.getPackName());
                            authorityMaterielVO.setProductPic(productDetailVO.getProductPic());
                            authorityMaterielVO.setSkuCode(productDetailVO.getSkuCode());
                            authorityMaterielVO.setSkuName(productDetailVO.getSkuName());
                            authorityMaterielVO.setOldSpecCode(productDetailVO.getOldSpecCode());
                            authorityMaterielVO.setUnitName(productDetailVO.getUnitName());
                            listAuthorityMateriel.add(authorityMaterielVO);
                        }
                        list.addAll(listAuthorityMateriel);
                    }
                    return new PageResult<>(list, list.size());
                }else{
                    //限制方式按物料
                    List<AuthorityMaterielVO> list1 = new ArrayList<>();
                    List<AuthorityMateriel> list = authorityMaterielService.list(new QueryWrapper<AuthorityMateriel>().eq("manage_id",authorityManageId));
                    for (AuthorityMateriel authorityMateriel:list){
                        HashMap map = new HashMap();
                        map.put("skuCode",authorityMateriel.getSkuCode());
                        List<ProductDetailVO> listProductDetail = productDetailService.list4app(map);
                        for (ProductDetailVO productDetailVO:listProductDetail){
                            AuthorityMaterielVO authorityMaterielVO = new AuthorityMaterielVO();
                            authorityMaterielVO.setProductBrandName(productDetailVO.getBrandName());
                            authorityMaterielVO.setManageId(authorityManageId);
                            if (authorityManageVO.getAuthorizedQuantity()!=null){authorityMaterielVO.setNumber(authorityMateriel.getNumber());}
                            if (authorityManageVO.getLineOfCredit()!=null){authorityMaterielVO.setAmount(authorityMateriel.getAmount());}
                            authorityMaterielVO.setPackName(productDetailVO.getPackName());
                            authorityMaterielVO.setProductPic(productDetailVO.getProductPic());
                            authorityMaterielVO.setSkuCode(productDetailVO.getSkuCode());
                            authorityMaterielVO.setSkuName(productDetailVO.getSkuName());
                            authorityMaterielVO.setOldSpecCode(productDetailVO.getOldSpecCode());
                            authorityMaterielVO.setUnitName(productDetailVO.getUnitName());
                            authorityMaterielVO.setId(authorityMateriel.getId());
                            list1.add(authorityMaterielVO);
                        }
                    }
                    return new PageResult<>(list1, list1.size());
                }
            }

        }

        return null;

    }

    @Override
    @Transactional
    public boolean removeAll(Long authorityManageId) {
        //QueryWrapper<AboveTheQuotaApply> applyQueryWrapper = new QueryWrapper<AboveTheQuotaApply>();
        //applyQueryWrapper.eq("authority_manage_id", authorityManageId);
        //List<AboveTheQuotaApply> applyList = aboveTheQuotaApplyDao.selectList(applyQueryWrapper);
        //if(null != applyList && applyList.size() >0){
        //    throw new BusinessException("此权限组已经存在超额领新记录,不允许删除!");
        //}
        AuthorityManage authorityManage = baseMapper.selectById(authorityManageId);
        authorityManage.setStatus(1L);

        QueryWrapper<AuthorityMateriel> queryWrapper = new QueryWrapper<AuthorityMateriel>();
        queryWrapper.eq("manage_id",authorityManageId);
        QueryWrapper<AuthorityMember> wrapper = new QueryWrapper<AuthorityMember>();
        wrapper.eq("authority_manage_id",authorityManageId);
        QueryWrapper<CountQuota> countWrapper = new QueryWrapper<CountQuota>();
        countWrapper.eq("authority_manage_id",authorityManageId);
        QueryWrapper<ReceiveRecord> recordWrapper = new QueryWrapper<ReceiveRecord>();
        recordWrapper.eq("authority_manage_id",authorityManageId);
        //if (baseMapper.deleteById(authorityManageId)>0&&authorityMaterielService.remove(queryWrapper)&&authorityMemberService.remove(wrapper)&&countQuotaService.remove(countWrapper)&&receiveRecordService.remove(recordWrapper)){
        //    return true;
        //}
        if (baseMapper.updateById(authorityManage) >0 && authorityMaterielService.remove(queryWrapper)&&authorityMemberService.remove(wrapper)&&countQuotaService.remove(countWrapper)&&receiveRecordService.remove(recordWrapper)){
            return true;
        }
        return false;
    }

}
